from flask import Flask, request, jsonify, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import os

# 创建Flask应用（禁用默认静态文件夹）
app = Flask(__name__, static_folder='', static_url_path='')
CORS(app)

# 数据库配置
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# 用户模型定义
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True, nullable=False)
    pwd = db.Column(db.String(50), nullable=False)
    age = db.Column(db.Integer)
    gender = db.Column(db.String(10))
    phone = db.Column(db.String(20))

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'age': self.age,
            'gender': self.gender,
            'phone': self.phone
        }

# 创建数据库表
with app.app_context():
    db.create_all()

# ---------------- API接口实现 ----------------
@app.route('/login', methods=['GET', 'POST'])
def login():
    """用户登录接口"""
    if request.method == 'GET':
        username = request.values.get('name')
        pwd = request.values.get('pwd')
    elif request.method == 'POST':
        try:
            username = request.values['name']
            pwd = request.values['pwd']
        except KeyError:
            ret = {'code': 10001, 'message': '参数不能为空！'}
            return jsonify(ret)

    if username and pwd:
        user = User.query.filter_by(name=username, pwd=pwd).first()
        if user:
            ret = {'code': 0, 'message': '登录成功', 'data': user.to_dict()}
            return jsonify(ret)
        else:
            ret = {'code': -1, 'message': '账号密码错误'}
            return jsonify(ret)
    else:
        ret = {'code': 10001, 'message': '参数不能为空！'}
        return jsonify(ret)

@app.route('/add', methods=['POST'])
def add_user():
    """添加用户接口"""
    try:
        data = request.get_json()
        name = data.get('name')
        pwd = data.get('pwd')
        age = data.get('age')
        gender = data.get('gender')
        phone = data.get('phone')
    except KeyError:
        ret = {'code': 10001, 'message': '参数不能为空！'}
        return jsonify(ret)

    if User.query.filter_by(name=name).first():
        ret = {'code': 10002, 'message': '用户已存在！'}
        return jsonify(ret)

    new_user = User(name=name, pwd=pwd, age=age, gender=gender, phone=phone)
    db.session.add(new_user)
    db.session.commit()

    ret = {'code': 0, 'message': '添加成功', 'data': new_user.to_dict()}
    return jsonify(ret)

@app.route('/delete/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    """删除用户接口"""
    user = User.query.get(user_id)
    if not user:
        ret = {'code': 10003, 'message': '用户不存在！'}
        return jsonify(ret)

    db.session.delete(user)
    db.session.commit()

    ret = {'code': 0, 'message': '删除成功'}
    return jsonify(ret)

@app.route('/update/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    """更新用户接口"""
    user = User.query.get(user_id)
    if not user:
        ret = {'code': 10003, 'message': '用户不存在！'}
        return jsonify(ret)

    try:
        data = request.get_json()
        name = data.get('name')
        pwd = data.get('pwd')
        age = data.get('age')
        gender = data.get('gender')
        phone = data.get('phone')
    except KeyError:
        ret = {'code': 10001, 'message': '参数不能为空！'}
        return jsonify(ret)

    if name and User.query.filter_by(name=name).first() and user.name != name:
        ret = {'code': 10002, 'message': '用户名已存在！'}
        return jsonify(ret)

    if name:
        user.name = name
    if pwd:
        user.pwd = pwd
    if age is not None:
        user.age = age
    if gender:
        user.gender = gender
    if phone:
        user.phone = phone

    db.session.commit()

    ret = {'code': 0, 'message': '更新成功', 'data': user.to_dict()}
    return jsonify(ret)

@app.route('/get/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """查询单个用户接口"""
    user = User.query.get(user_id)
    if not user:
        ret = {'code': 10003, 'message': '用户不存在！'}
        return jsonify(ret)

    ret = {'code': 0, 'message': '查询成功', 'data': user.to_dict()}
    return jsonify(ret)

@app.route('/get_all', methods=['GET'])
def get_all_users():
    """查询所有用户接口"""
    users = User.query.all()
    users_list = [user.to_dict() for user in users]

    ret = {'code': 0, 'message': '查询成功', 'data': users_list}
    return jsonify(ret)

# ---------------- 静态文件服务 ----------------
@app.route('/')
def serve_index():
    """提供前端首页"""
    return send_from_directory('.', 'index.html')

@app.route('/<path:path>')
def serve_static_files(path):
    """提供静态文件"""
    return send_from_directory('.', path)

# ---------------- 显式导出对象 ----------------
__all__ = ['app', 'db', 'User']

# ---------------- 启动服务 ----------------
if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=8081)